﻿/*
    Copyright (C) <2007-2013> Kay Diefenthal

    SimpleRadio is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    SimpleRadio is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with SimpleRadio.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;
using SimpleRadio.Logging;

namespace SimpleRadio
{
    /// <summary>
    /// <see cref="DefaultModel"/> Class.
    /// </summary>
    public class DefaultModel : ModelItem
    {
        #region Private Fields

        private readonly HistoryOrientedPageSession _session;
        private readonly AddInHost _host;
        private Int32 _modeIndex;

        #endregion

        #region Constructors

        /// <summary>
        /// Initialize a new Instance of <see cref="DefaultModel"/> Class.
        /// </summary>
        public DefaultModel()
            : this(null, null)
        {
        }

        /// <summary>
        /// Initialize a new Instance of <see cref="DefaultModel"/> Class.
        /// </summary>
        /// <param name="session">session <seealso cref="Microsoft.MediaCenter.Hosting.HistoryOrientedPageSession"/></param>
        /// <param name="host">host <seealso cref="Microsoft.MediaCenter.Hosting.AddInHost"/></param>
        public DefaultModel(HistoryOrientedPageSession session, AddInHost host)
        {
            _session = session;
            _host = host;
        }

        #endregion

        #region Properties

        /// <summary>
        /// The MediaCenterEnvironment
        /// </summary>
        public MediaCenterEnvironment MediaCenterEnvironment
        {
            get
            {
                if (_host == null) return null;
                return _host.MediaCenterEnvironment;
            }
        }

        /// <summary>
        /// The ModeIndex
        /// </summary>
        public int ModeIndex
        {
            get { return _modeIndex; }
            set
            {
                _modeIndex = value; FirePropertyChanged("ModeIndex");
            }
        }
        #endregion

        #region Private Methods

        /// <summary>
        /// CreateDefaultView
        /// </summary>
        /// <returns>returns a DefaultView Object or null</returns>
        private DefaultView CreateDefaultView()
        {
            try
            {
                _modeIndex = Properties.Settings.Default.Mode;

                var view = new DefaultView();
                var contentList = new VirtualList(view, null) { EnableSlowDataRequests = true };
                view.Content = contentList;
                CreateSortFilterTypes(view);
                view.ServiceInvoked += (sender, args) => MediaCenterEnvironment.PlayMedia(MediaType.Audio, ((Service)sender).MediaPath, false);
                return view;
            }
            catch (Exception exception)
            {
                Logger.Error(String.Format("{0} :{1} -{2} ", "CreateDefaultView", exception.Message, exception.StackTrace));
                return null;
            }
        }

        /// <summary>
        /// CreateSortFilterTypes
        /// </summary>
        /// <param name="view">view <see cref="DefaultView"/></param>
        private void CreateSortFilterTypes(DefaultView view)
        {
            try
            {
                ModelItem genre = new SortFilter(view, "Genre", SortFilterTypes.Genre);
                ModelItem region = new SortFilter(view, "Region", SortFilterTypes.Region);
                var list = new ArrayListDataSet(view)
                {
                    genre,
                    region
                };
                var choice = new Choice(view, null, list) { Chosen = list[_modeIndex] };
                view.SortFiltersChanged += delegate(object sender, EventArgs e)
                {
                    var defaultView = (DefaultView)sender;
                    var selected = (SortFilter)defaultView.SortFilters.Chosen;
                    _modeIndex = defaultView.SortFilters.ChosenIndex;
                    CreateBaseFilter(defaultView, selected);
                };
                view.SortFilters = choice;
            }
            catch (Exception exception)
            {
                Logger.Error(String.Format("{0} :{1} -{2} ", "CreateSortFilterTypes", exception.Message, exception.StackTrace));
            }
        }

        /// <summary>
        /// CreateBaseFilter
        /// </summary>
        /// <param name="view">DefaultView Object <seealso cref="DefaultView"/></param>
        /// <param name="sortFilter">sortFilter <seealso cref="SortFilter"/></param>
        private void CreateBaseFilter(DefaultView view, SortFilter sortFilter)
        {
            try
            {
                var list = new ArrayListDataSet(view);
                var countries = Utils.RetrieveCountries(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SimpleRadio\\Services.xml");
                list.CopyFrom(countries);
                var choice = new Choice(view, null, list) { Chosen = list[0] };
                view.BaseFilterChanged += delegate(object sender, EventArgs e)
                {
                    var defaultView = (DefaultView)sender;
                    var selected = (String)defaultView.BaseFilter.Chosen;
                    CreateSubFilter(view, selected, sortFilter);
                };
                view.BaseFilter = choice;
            }
            catch (Exception exception)
            {
                Logger.Error(String.Format("{0} :{1} -{2} ", "CreateBaseFilter", exception.Message, exception.StackTrace));
            }
        }

        /// <summary>
        /// CreateSubFilter
        /// </summary>
        /// <param name="view">DefaultView Object <seealso cref="DefaultView"/></param>
        /// <param name="value">Base Filter <seealso cref="System.String"/></param>
        /// <param name="sortFilter"> Sort Filter <seealso cref="SortFilter"/></param>
        private void CreateSubFilter(DefaultView view, String value, SortFilter sortFilter)
        {
            try
            {
                var list = new ArrayListDataSet(view);
                list.Clear();
                switch (sortFilter.SortFilterType)
                {
                    case SortFilterTypes.Genre:
                        var genres = Utils.RetrieveGenreforServices(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SimpleRadio\\Services.xml", value);
                        list.CopyFrom(genres);
                        var genreChoice = new Choice(view, null, list) { Chosen = list[0] };
                        view.SubFilterChanged += delegate(object sender, EventArgs e)
                        {
                            var defaultView = (DefaultView)sender;
                            var selected = (String)defaultView.SubFilter.Chosen;
                            CreateContent(defaultView, selected, sortFilter);
                        };
                        view.SubFilter = genreChoice;
                        break;

                    case SortFilterTypes.Region:
                        var regions = Utils.RetrieveRegionforServices(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SimpleRadio\\Services.xml", value);
                        list.CopyFrom(regions);
                        var regionChoice = new Choice(view, null, list) { Chosen = list[0] };
                        view.SubFilterChanged += delegate(object sender, EventArgs e)
                        {
                            var defaultView = (DefaultView)sender;
                            var selected = (String)defaultView.SubFilter.Chosen;
                            CreateContent(defaultView, selected, sortFilter);
                        };
                        view.SubFilter = regionChoice;
                        break;
                }
            }
            catch (Exception exception)
            {
                Logger.Error(String.Format("{0} :{1} -{2} ", "CreateSubFilter", exception.Message, exception.StackTrace));
            }
        }

        /// <summary>
        /// CreateContent
        /// </summary>
        /// <param name="view">DefaultView Object <seealso cref="DefaultView"/></param>
        /// <param name="value">Sub Filter <seealso cref="System.String"/></param>
        /// <param name="sortFilter"> Sort Filter <seealso cref="SortFilter"/></param>
        private void CreateContent(DefaultView view, String value, SortFilter sortFilter)
        {
            try
            {
                view.Content.Clear();
                IList<Service> services = null;
                switch (sortFilter.SortFilterType)
                {
                    case SortFilterTypes.Genre:
                        services = Utils.RetrieveGenreSortServices(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SimpleRadio\\Services.xml", (String)view.BaseFilter.Chosen, value);
                        break;
                    case SortFilterTypes.Region:
                        services = Utils.RetrieveRegionSortServices(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SimpleRadio\\Services.xml", (String)view.BaseFilter.Chosen, value);
                        break;
                }

                if (services != null)
                    foreach (var service in services)
                    {
                        view.Content.Add(service);
                    }
            }
            catch (Exception exception)
            {
                Logger.Error(String.Format("{0} :{1} -{2} ", "CreateContent", exception.Message, exception.StackTrace));
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// GoToDefaultView
        /// </summary>
        public void GoToDefaultView()
        {
            try
            {
                var uiProperties = new Dictionary<string, object>();
                uiProperties["DefaultView"] = CreateDefaultView();
                if (_session != null)
                {
                    _session.GoToPage("resx://SimpleRadio/SimpleRadio.Resources/DefaultView", uiProperties);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(String.Format("{0} :{1} -{2} ", "GoToDefaultView", exception.Message, exception.StackTrace));
            }
        }

        #endregion
    }
}
